package managers;

import java.util.List;

import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.TypedQuery;

import security.Encryption;

import entities.User;

@Stateless
@LocalBean
public class UserManager {
	@PersistenceContext
	EntityManager em;
	
	public User create(User u){
		em.persist(u);
		em.flush();
		return u;
	}
	public User update(User u){
		em.merge(u);
		em.flush();
		return u;
	}
	public void delete(int id){
		User list = getUser(id);
		if(list != null){
			em.remove(list);
			em.flush();
		}
	}
	
	public User getUser(int id){
		return em.getReference(User.class, id);
	}
	
	public User getUser(String findBy, boolean email){
		TypedQuery<User> users = em.createQuery("SELECT u FROM User u", User.class);
		User user = null;
		if(email){
			for(User u : users.getResultList()){
				if(u.getEmail().equals(findBy)){
					user = u; 
					break;
				}
			}
		}else{
			for(User u : users.getResultList()){
				if(u.getUsername().equals(findBy)){
					user = u;
					break;
				}
			}
		}
		
		return user;
	}

	public List<User> getUsers(){
		Query getUsers = em.createQuery("SELECT u FROM User u", User.class);
		return (List<User>) getUsers.getResultList();
	}
	public User getLoggedInUser(String username, String password){
		User tempUser = null;
		TypedQuery<User> getUsers = em.createQuery("SELECT u FROM User u", User.class);
		for(User u : getUsers.getResultList()){
			if(u.getUsername().equals(username) && u.getPassword().equals(Encryption.digest(password)))
				tempUser = u;
		}
		return tempUser;
	}
	public User getLoggedInUser(String username){
		TypedQuery<User> getUsers = em.createQuery("SELECT u FROM User u WHERE u.username = :username", User.class);
		getUsers.setParameter("username", username);
		
		return (User)getUsers.getSingleResult();
	}
}
